import { App } from 'vue';

import { FastCrud } from '@fast-crud/fast-crud';
import '@fast-crud/fast-crud/dist/style.css';
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars,no-unused-vars
import { FsExtendsUploader, FsExtendsEditor } from '@fast-crud/fast-extends';
import '@fast-crud/fast-extends/dist/style.css';
import UiNaive from '@fast-crud/ui-naive';
import { request } from '@/utils/http/service';
import { useCrudPermission } from '@/plugins/fast_crud/use-crud-permission';
import { IUserState, useUserStoreWidthOut } from '@/store/modules/user';

function install(app, options: any = {}) {
  app.use(UiNaive);
  app.use(FastCrud, {
    i18n: options.i18n,
    async dictRequest({ url }) {
      return await request({ url, method: 'get' });
    },
    /**
     * useCrud时会被执行
     * @param context，useCrud的参数
     */
    commonOptions(context: any = {}) {
      console.log('commonOptions execute ,context:', context);
      const opts = {
        table: {
          size: 'small',
          pagination: false,
        },
        search: {
          options: {
            size: 'medium',
          },
        },
        rowHandle: {
          align: 'center',
          buttons: {
            view: { text: null, icon: 'EyeOutlined', size: 'small' },
            edit: { text: null, icon: 'EditOutlined', size: 'small' },
            remove: { type: 'error', text: null, icon: 'DeleteOutlined', size: 'small' },
          },
          dropdown: {
            more: { size: 'small', type: 'link' },
          },
        },
        request: {
          // 查询参数转换
          transformQuery: ({ page, form, sort }) => {
            const order = sort == null ? {} : { column: sort.prop, asc: sort.asc };
            const currentPage = page.currentPage ?? 1;
            const limit = page.pageSize ?? 20;
            const offset = limit * (currentPage - 1);
            return {
              offset: offset,
              current: currentPage,
              size: page.pageSize,
              ...form,
              ...order,
            };
          },
          // page请求结果转换
          transformRes: ({ res }) => {
            return {
              currentPage: res?.data?.current || 1,
              pageSize: res?.data?.size || 20,
              ...res?.data,
            };
          },
        },
        form: {
          display: 'flex', //表单布局
          labelWidth: '100px', //表单label宽度
          wrapper: {
            is: 'n-drawer',
          },
        },
      };
      const crudPermission = useCrudPermission(context);
      return crudPermission.merge(opts);
    },
  });

  // fast-extends里面的扩展组件均为异步组件，只有在使用时才会被加载，并不会影响首页加载速度
  //安装editor
  app.use(FsExtendsEditor, {
    //编辑器的公共配置
    wangEditor: {},
  });
  //安装uploader 公共参数
  app.use(FsExtendsUploader, {
    defaultType: 'form',
    form: {
      action: '/storage/storage/upload-image',
      name: 'file',
      withCredentials: false,
      uploadRequest: async ({ action, file, onProgress }) => {
        // @ts-ignore
        const data = new FormData();
        data.append('file', file);
        console.log('自定义表单文件上传请求', file);
        const userStore = useUserStoreWidthOut();
        const token = userStore.getToken;
        const userInfo: IUserState = <IUserState>userStore.getUserInfo;
        return await request({
          url: action,
          method: 'post',
          headers: {
            Authorization: 'Bearer ' + token,
            tenant_code: userInfo?.tenantCode,
            'Content-Type': 'multipart/form-data',
          },
          data,
          onUploadProgress(progress) {
            onProgress({ percent: Math.round((progress.loaded / progress.total) * 100) });
          },
        });
      },
      successHandle(ret) {
        // 上传完成后的结果处理， 此处应返回格式为{url:xxx}
        console.log(ret);
        return { url: 'http://oss.endpoint.com/' + ret?.data?.path + ret?.data?.filename };
      },
    },
  });
}

export default {
  install,
};

export function setupFastCrud(app: App<Element>, options: any = {}) {
  install(app, options);
}
